package com.aynu.gulimall.product.exception;

import com.aynu.common.exception.BizCodeEnume;
import com.aynu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author mj
 * @version 1.0
 * @date 2020/6/21 22:29
 * 集中处理异常
 */
@Slf4j
//@ResponseBody
//@ControllerAdvice(basePackages = "com.aynu.gulimall.product.controller")
@RestControllerAdvice(basePackages = "com.aynu.gulimall.product.controller")
public class gulimallExceptionControllerAdvice
{

    //字段校验错误处理
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerValidException(MethodArgumentNotValidException e)
    {
        log.error("数据校检出现异常：{},异常类型：{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();

        Map<String,String> map = new HashMap<>();
        //循环出错误信息
        bindingResult.getFieldErrors().forEach((fieldError) ->{
            //获得字段出错getField()，默认提示信息为getDefaultMessage()
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        //返回错误信息，code，msg，data：map
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMessage()).put("data",map);
    }

    //未知错误处理
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable)
    {
        log.error("错误：",throwable);
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMessage());
    }
}
